package features.advance.ch3;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;

public class ThreadEchoServer {
    public static void main(String[] args) {
        try{
            int i = 1;
            ServerSocket s = new ServerSocket(8189);
            while(true){
                Socket incoming = s.accept();
                System.out.println("Spawning "+i);
                Runnable r = new ThreadEchoHandler(incoming);
                Thread t = new Thread(r);
                t.start();
                i++;
            }
         }catch (Exception e){
            e.printStackTrace();
        }
    }
}

class ThreadEchoHandler implements Runnable{
    private Socket incoming;
    public ThreadEchoHandler(Socket incoming){
        this.incoming = incoming;
    }
    @Override
    public void run() {
        try{
            InputStream inStream = incoming.getInputStream();
            OutputStream outStream = incoming.getOutputStream();
            Scanner scanner = new Scanner(inStream);
            PrintWriter out = new PrintWriter(outStream, true);
            out.println("Hello! Enter BYE to exit.");
            boolean done = false;
            while(!done && scanner.hasNextLine()){
                String line = scanner.nextLine();
                out.println("Echo: "+line);
                if (line.trim().equals("BYE")) done = true;
            }

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            try {
                incoming.close();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }
}

